package com.sxj.corejava.code13_JDBC;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Test03_单表操作 {

    public static void main(String[] args) throws DataAccessException {
        User user = new User("alice", "111111", "13612345676", "江苏-南京");
        User user2 = new User("jack", "222222", "13612345676", "江苏-南京");
        User user3 = new User("lucy", "333333", "13612345676", "江苏-南京");
        User user4 = new User("李四", "444444", "13612345676", "江苏-南京");
        User user5 = new User("王五", "555555", "13612345676", "江苏-南京");
        User user6 = new User("李兰", "123456", "13612345676", "江苏-南京");
        insertUser(user);
        insertUser(user2);
        insertUser(user3);
        insertUser(user4);
        insertUser(user5);
        insertUser(user6);
//        List<User> users = selectAll();
//        for (User user : users) {
//            System.out.println(user);
//        }
//        User user = new User(5,"张三", "555555", "13612345678", "江苏-苏州");
//        updateUser(user);

//        deleteById(4);
//        User user = selectById(1);
//        System.out.println(user);
    }

    public static void insertUser(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JDBCUtil.getConnection();
//            String sql = "insert into t_user(username,password,phone,address) values(?,?,?,?)";
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address) ")
                    .append(" values")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            int row = ps.executeUpdate();
            System.out.println("Query OK, " + row + " row affected");
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException(e);
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

    public static List<User> selectAll() throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException(e);
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }
        return users;
    }

    public static void updateUser(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8", "root", "root");
            // 3.获取状态集
            String sql = new StringBuffer()
                    .append(" update t_user ")
                    .append(" set ")
                    .append("   username = ?, ")
                    .append("   password = ?, ")
                    .append("   phone = ?, ")
                    .append("   address = ? ")
                    .append(" where id = ?")
                    .toString();
            ps = conn.prepareStatement(sql);
            // 根据sql语句中的?来设置参数
            // 每一个?表示需要一个参数,且参数的顺序与?的顺序完全一致
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.setInt(5, user.getId());
            // 执行DML操作
            ps.executeUpdate();
            System.out.println("提示:恭喜您,修改成功!");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void deleteById(Integer id) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JDBCUtil.getConnection();
            String sql = "delete from t_user where id = ? ";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            // 执行DML操作
            ps.executeUpdate();
            System.out.println("提示:恭喜您,删除成功");
        } catch (DataAccessException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public static User selectById(Integer id) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = JDBCUtil.getConnection();
            String sql = "select id,username,password,phone,address from t_user where id = ? ";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            while (rs.next()) {
                // 查询到数据了
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
            }
        } catch (DataAccessException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }
}
